﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace GrayParrot.Core.Serialization
{
    public static class SerializationUtility
    {
        /// <summary>
        /// Serializes the object using XML format.
        /// </summary>
        public static string SerializeAsXml(this object obj)
        {
            var type = obj.GetType();
            var xmlSerializer = new XmlSerializer(type);

            using (var memStream = new MemoryStream())
            {
                xmlSerializer.Serialize(memStream, obj);

                return Encoding.Default.GetString(memStream.ToArray());
            }
        }

        /// <summary>
        /// Deserializes the specified XML string to an object of the specified type T.
        /// </summary>
        public static T DeserializeAsXml<T>(this string xmlString)
        {
            var xmlSerializer = new XmlSerializer(typeof(T));

            using (var memStream = new MemoryStream(Encoding.Default.GetBytes(xmlString)))
            {
                return (T)xmlSerializer.Deserialize(memStream);
            }
        }
    }
}
